import os
from google.appengine.ext.webapp import template

from google.appengine.ext import webapp

from models.Topics import *
from models.Groups import *
from models.Users import *
from models.Audit import *
from models.Authentication import *


"""------------------------------------------------------------------------
NewTopic
------------------------------------------------------------------------"""
class NewTopic(webapp.RequestHandler):
  
  def get(self,groupID):
    
    """Responds to get requests to the controller"""
    ourUser = get_current_user(self.request)
    if not ourUser:
      return self.redirect("/login")
    template_values = {"form" : TopicForm(),"groupID":groupID}
    path= os.path.join(os.path.dirname(__file__), "../templates/newtopic.html")
    self.response.out.write(template.render(path, template_values))

  def post(self,groupID):
    ourUser = get_current_user(self.request)
    if not ourUser:
      return self.redirect("/login")
    data = TopicForm(data=self.request.POST)
    
    if(data.is_valid()):
      
      currUser = get_current_user(self.request)

      entity = data.save(commit=False)
      entity.group_id = int(groupID)
      entity.author = currUser.key().id()
      entity.put()


      audit = Audit(
          ip = self.request.remote_addr,
          action = "New Topic",
          date = entity.date_created,
          userID = currUser.key().id(),
          objectID = entity.key().id() 
      )
      audit.setTopic()
      audit.put()

      self.redirect('/topic/'+str(entity.key().id()))
    else:
      template_values = {"form" : data,"groupID":groupID}
      path= os.path.join(os.path.dirname(__file__), "../templates/newtopic.html")
      self.response.out.write(template.render(path, template_values))



"""------------------------------------------------------------------------
DeleteTopic
------------------------------------------------------------------------"""
class DeleteTopic(webapp.RequestHandler):
    def get(self,topicID):
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        
        topic = Topic.get_by_id(int(topicID))
        groupID = topic.group_id

        currUser = get_current_user(self.request)

        audit = Audit(
            ip = self.request.remote_addr,
            action = "Delete Topic",
            date = topic.date_created,
            userID = currUser.key().id(),
            objectID = topic.key().id() 
        )
        audit.setTopic()
        audit.put()

        topic.delete()
        self.redirect('/group/'+str(groupID));
        


"""------------------------------------------------------------------------
ModifyTopic
------------------------------------------------------------------------"""
class ModifyTopic(webapp.RequestHandler):
    def get(self,topicID):
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        topic = Topic.get_by_id(int(topicID))

        template_values = {"topic":topic}
        path = os.path.join(os.path.dirname(__file__),"../templates/ModifyTopic.html")
        self.response.out.write(template.render(path,template_values))
    def post(self,topicID):
        ourUser = get_current_user(self.request)
        if not ourUser:
          return self.redirect("/login")
        topic = Topic.get_by_id(int(topicID))

        currUser = get_current_user()

        audit = Audit(
            ip = self.request.remote_addr,
            action = "Modify Topic (Changed topic to: "+self.request.get('topic')+ ")",
            date = topic.date_created,
            userID = currUser.key().id(),
            objectID = topic.key().id() 
        )
        audit.setTopic()
        audit.put()

        topic.topic = self.request.get('topic')
        topic.put()
        self.redirect('/topic/'+str(topic.key().id()))
        





"""------------------------------------------------------------------------
ViewTopicsByGroup
------------------------------------------------------------------------"""
class ViewTopicsByGroup(webapp.RequestHandler):
  def get(self,groupID):
    #messages = Message.all()
    #template_values = {"messages":messages}
    ourUser = get_current_user(self.request)
    if not ourUser:
      return self.redirect("/login")
    topics = Topic.all()
    topics.filter("group_id =", int(groupID))
   
    topicsWithCount = []
    
    # check to see if the user is a moderator
    moderator = get_current_user(self.request).moderator
   
    # loop through all the topics to get the message count
    for topic in topics:
        messages = Message.all()
        messages.filter("topic =",topic.key().id())
        count = messages.count()
        topicsWithCount.append({"topic":topic,"count":count})
        
    group = Group.get_by_id(int(groupID))
    # set up the values for the template and the render the template
    template_values = {"topics":topicsWithCount,"group":group, "moderator":moderator}
    path= os.path.join(os.path.dirname(__file__), "../templates/ViewTopicsByGroup.html")
    self.response.out.write(template.render(path, template_values))

